package logic

import (
	"context"
	"fmt"
	"math/rand"
	"net/http"
	"strconv"
	"time"

	"github.com/zeromicro/go-zero/core/logx"

	"Junior_two/video/videorpc/internal/model"
	"Junior_two/video/videorpc/internal/utils"

	"github.com/smartwalle/alipay/v3"

	"Junior_two/video/videorpc/internal/svc"
	"Junior_two/video/videorpc/pb/videoRpc"
)

type RechargeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRechargeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RechargeLogic {
	return &RechargeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

var (
	appID string
	//私钥
	privateKey string
	//公钥
	aliPublicKey string
	//ali客户端
	client *alipay.Client
)

func init() {
	appID = utils.AppId
	privateKey = utils.PrivateKey
	aliPublicKey = utils.AliPublicKey
	client, _ = alipay.New(appID, privateKey, false)
	client.LoadAlipayCertPublicKey(aliPublicKey)
}

// Recharge 充值余额
func (l *RechargeLogic) Recharge(in *videoRpc.RechargeRequest) (*videoRpc.RechargeResponse, error) {
	// todo: add your logic here and delete this line
	//支付宝沙箱支付 充值余额
	subject := "test" + fmt.Sprintf("%d", rand.Intn(10000))
	//订单编号 第三方接口需要
	outTradeNo := time.Now().Unix()
	//调用接口
	url := utils.AliPay(subject, strconv.FormatInt(outTradeNo, 10), client, in.Balance)
	//获取原有数据
	u := model.GetUserData(in.UserId)
	f, _ := strconv.ParseFloat(in.Balance, 64)
	//充值 快币
	u.UserBalance += f
	//修改数据库中余额
	err := model.UpdateBalance(&model.User{
		Id:          in.UserId,
		UserBalance: u.UserBalance,
	})
	if err != nil {
		return &videoRpc.RechargeResponse{
			Msg:  "充值失败",
			Code: http.StatusAccepted,
			Data: "",
		}, nil
	}
	//返回接口 进行访问支付宝接口 进行支付
	return &videoRpc.RechargeResponse{
		Msg:  "请前往充值",
		Code: http.StatusOK,
		Data: url,
	}, nil
}
